package com.xyy.saas.payment.util;

import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;

@Slf4j
public class PojoConvertUtil extends BeanUtils {

    /**
     * 空判断
     * @param obj : 实体
     * @param blankFields : 判空字段
     */
    public static void checkBlank(Object obj, List<String> blankFields) throws PaymentException, IllegalAccessException {
        if (null == obj) {
            throw new PaymentException(ResultCodeEnum.PARAM_ERROR, ResultCodeEnum.PARAM_ERROR.getDisplayMsg());
        }
        Class<?> aClass = obj.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            if (blankFields.contains(declaredField.getName())) {
                Object value = declaredField.get(obj);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    log.info("参数:{}不允许为空！", declaredField.getName());
                    throw new PaymentException(ResultCodeEnum.PARAM_ERROR, ResultCodeEnum.PARAM_ERROR.getDisplayMsg() + "：" + declaredField.getName());
                }
            }
        }
    }

    /**
     * 将具有相同属性的类型进行转换
     */
    public static <T> T convertPojo(Object sources, Supplier<T> target) {
        if (null == sources) {
            return null;
        }
        T t = target.get();
        copyProperties(sources, t);
        return t;
    }


    public static <S, T> List<T> copyList(List<S> sources, Supplier<T> target) {
        if (CollectionUtils.isEmpty(sources)) {
            return Collections.EMPTY_LIST;
        }
        List<T> list = new ArrayList<>(sources.size());
        for (S source : sources) {
            T t = target.get();
            copyProperties(source, t);
            list.add(t);
        }
        return list;
    }

}